import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, Radio, Cascader, Select, message} from 'antd';

import {
  getComBaseInfoById,
  publicCommonDictGetDictByCodeTypes, systemPlatNewsVerificationCode,
  updateComBaseInfoById,
} from "../../../services/api";

import PCascader from "../../../components/Pro/PCascader";
import bcx_utils from "../../../common/bcx_utils";


const FormItem = Form.Item;
const {Option} = Select;
@Form.create()

/**
 * 基础信息
 */
export default class InitialBasicInformation extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // count: 0,
      companyInfo: {},//公司信息
      industryType: [],//行业类型
      economicType: [],//经济类型
      comType: [],//企业类型
      institutionType: [], //机构类型
      IsBranch: "",
    };

  }


  /******************************生命周期******************************/

  componentDidMount = () => {
    this.publicCommonDictGetDictByCodeTypes();
    // this.getDistrictData();
    /* //MSelect 和 form 结合使用，等待完善
     MSelect(["economicType", "comType", "institutionType"], (data) => {
       this.setState({PMSelect: data});
     });*/
  }
  /******************************ajax请求******************************/
    //获取企业信息
  getComBaseInfoById = () => {
    getComBaseInfoById({}).then(
      ({data}) => {
        this.setState({companyInfo: data});
      },
      (err) => {
        console.log(err);
      }
    );
  }
  //查询字典
  publicCommonDictGetDictByCodeTypes = () => {
    let tmp = {codeTypes: ["industryType", "economicType", "comType", "institutionType"]};
    publicCommonDictGetDictByCodeTypes(tmp).then(
      ({data: {industryType, economicType, comType, institutionType}}) => {

        this.setState({industryType, economicType, comType, institutionType});

        this.getComBaseInfoById();
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //修改企业基本信息
  updateComBaseInfoById = (ajaxUpdate, resolve) => {
    updateComBaseInfoById(ajaxUpdate).then(
      ({msg}) => {
        message.success(msg, 1.5, () => resolve());
        this.props.nextStep();
      },
      (err = "") => {
        console.log(err);
      }
    );
  }

  /******************************相关事件******************************/

    //表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const {address: [regProvince, regCity, regArea], comType, economicType, isBranchCom, parentComName, parentComRep, parentComTel, regAddress, telePhone, parentComCerNo} = values;
        const {comId, comName, fax, industryType, institutionType} = this.state.companyInfo;
        const ajaxUpdate = {
          // comId,
          comName,
          telePhone,
          fax,
          regProvince,
          regCity,
          regArea,
          regAddress,
          economicType,
          industryType,
          comType,
          institutionType,
          isBranchCom,
          parentComName,
          parentComRep,
          parentComTel,
          parentComCerNo
        };
        console.log(ajaxUpdate);
        bcx_utils.preventRepeatAsync(callback => callback((resolve) => {
          this.updateComBaseInfoById(ajaxUpdate, resolve);
        }));
      }
    });
  }

  //是否为公司
  onChangeIsBranch = (e) => {
    console.log('radio checked', e.target.value);
    const companyInfo = this.state.companyInfo;
    companyInfo.isBranchCom = e.target.value;
    this.setState({companyInfo});
  }
  /******************************render******************************/
    //经济类型
  renderEconomicType = () => {
    return this.state.economicType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }
  //企业类型
  renderComType = () => {
    return this.state.comType.map(val => (
      <Option
        value={val.codeValue + ""}
        key={val.codeValue}>{val.label}</Option>
    ));
  }
  //行业类型
  renderIndustryType = () => {
    const {industryType} = this.state;
    const industryTypeItem = this.state.companyInfo.industryType || "";
    return industryType.find(val => val.codeValue === industryTypeItem).label;
  }
  //机构类型
  renderinstitutionType = () => {
    const {institutionType} = this.state;
    const institutionTypeItem = this.state.companyInfo.institutionType || "";
    return institutionType.find(val => val.codeValue === institutionTypeItem).label;
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: {span: 6},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 12},
        sm: {span: 12},
      },
    };
    const {
      comName = "",
      economicType = "",
      comType = "",
      telePhone = "",
      regAddress = "",
      isBranchCom = "0",
      parentComName = "0",
      parentComCerNo = "0",
      parentComRep = "0",
      parentComTel = "0",
      regProvince = "",
      regCity = "",
      regArea = "",
    } = this.state.companyInfo;

    return (
      <Container>
        <header className="password-header">完善企业基础信息</header>
        {Object.keys(this.state.companyInfo).length !== 0 && (
          <Form onSubmit={this.handleSubmit} style={{marginTop: 24}}
          >
            <FormItem {...formItemLayout} label="当前企业">
              <span>{comName}</span>
            </FormItem>

            <FormItem {...formItemLayout} label="所属行业"
            >
              <span>{this.renderIndustryType()}</span>
            </FormItem>

            <FormItem {...formItemLayout} label="机构类型"
            >
              <span>{this.renderinstitutionType()}</span>
            </FormItem>

            <FormItem {...formItemLayout} label="经济类型"
            >
              {getFieldDecorator('economicType', {
                initialValue: economicType,
                rules: [{
                  required: true, message: '请输入',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderEconomicType()}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="企业类型"
            >
              {getFieldDecorator('comType', {
                initialValue: comType,
                rules: [{
                  required: true, message: '请选择',
                }],
              })(
                <Select placeholder="请选择">
                  {this.renderComType()}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="联系电话"
            >
              {getFieldDecorator('telePhone', {
                initialValue: telePhone,
                rules: [{
                  pattern: /(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\(\d{3}\))|(\d{3}\-))?(1[358]\d{9})$)/,
                  message: '请输入正确手机号码或者固定电话，固定电话以-隔开',
                }, {required: true, message: '请输入联系电话'}],
              })(
                <Input placeholder="请输入手机号码"/>
              )}
            </FormItem>


            <FormItem {...formItemLayout} label="注册地址"
            >
              {getFieldDecorator('address', {
                initialValue: [regProvince, regCity, regArea],
                rules: [{type: 'array', required: true, message: '注册地址不能为空!'}],
              })(
                <PCascader placeholder="请选择"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="详细地址" colon={false} className="regAddress"
            >
              {getFieldDecorator('regAddress', {
                initialValue: regAddress,
                rules: [{
                  required: true, message: '请输入公司注册详细地址',
                }],
              })(
                <Input placeholder="请填写公司注册详细地址" maxLength="100"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="是否为分公司"
            >
              {getFieldDecorator('isBranchCom', {
                initialValue: isBranchCom,
                rules: [{
                  required: true, message: '请选择分公司',
                }],
              })(
                <Radio.Group onChange={this.onChangeIsBranch}>
                  <Radio value="1">是</Radio>
                  <Radio value="0">否</Radio>
                </Radio.Group>
              )}
            </FormItem>


            {isBranchCom === "1" && (
              <div>
                <FormItem {...formItemLayout} label="总公司营业执照号"
                >
                  {getFieldDecorator('parentComCerNo', {
                    initialValue: parentComCerNo || "",
                    rules: [{
                      required: true, message: '总公司营业执照号',
                    }, {
                      pattern: /^[A-Za-z0-9]{1,20}$/, message: '请输入最大20个字符的名称'
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20"/>
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="总公司名称"
                >
                  {getFieldDecorator('parentComName', {
                    initialValue: parentComName || "",
                    rules: [{
                      required: true, message: '总公司名称',
                    }, {
                      pattern: /^[\u4e00-\u9fa5\（\）]{1,50}$/, message: '请输入最大50个字符的名称'
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20"/>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label="总公司法人"
                >
                  {getFieldDecorator('parentComRep', {
                    initialValue: parentComRep || "",
                    rules: [{
                      required: true, message: '请输入 总公司法人',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength="20"/>
                  )}
                </FormItem>

                <FormItem {...formItemLayout} label="总公司联系电话"
                >
                  {getFieldDecorator('parentComTel', {
                    initialValue: parentComTel || "",
                    rules: [{
                      pattern: /(^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$)|(^((\(\d{3}\))|(\d{3}\-))?(1[358]\d{9})$)/,
                      message: '请输入正确手机号码或者固定电话，固定电话以-隔开!',
                    },
                      {
                        required: true, message: '请输入总公司联系电话',
                      }],
                  })(
                    <Input placeholder="请输入" maxLength="12"/>
                  )}
                </FormItem>
              </div>
            )}

            <FormItem {...formItemLayout} label=" " colon={false}
            >
              {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
              <Button className="submit" type="primary" htmlType="submit">保存</Button>
            </FormItem>
          </Form>
        )}
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .detailedAddress{
        .ant-form-item-required:before{
            content:" ";
        }
    }
}`;
